package com.zhanqiao.Dao;

import com.zhanqiao.Utils.GetDataSourceUtil;
import com.zhanqiao.domain.ArticleBean;
import com.zhanqiao.domain.ProductBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class SelectRepositoryProductDao implements ArticleDao {

    @Override
    public int insertArticle(ProductBean productBean, String tag) {
        return 0;
    }

    @Override
    public int deleteProduct(int pid) throws SQLException {
        DataSource ds = GetDataSourceUtil.getDataSource();
        QueryRunner queryRunner = new QueryRunner(ds);
        return queryRunner.update("update product set pstatus=3 where pid=" + pid);
    }

    @Override
    public List<ArticleBean> selectAll() {

        return null;
    }

    @Override
    public int updateProduct(Integer pid, String pname, Integer psaleprice, Integer pcount) throws SQLException {
        DataSource ds = GetDataSourceUtil.getDataSource();
        QueryRunner queryRunner = new QueryRunner(ds);
        return queryRunner.update("update product set pstatus=2 where pid=" + pid);
    }


    public List<ProductBean> selectAll(String page,String limit) {
        DataSource ds = GetDataSourceUtil.getDataSource();
        QueryRunner queryRunner = new QueryRunner(ds);
        int pages = Integer.parseInt(page);
        int counts = Integer.parseInt(limit);
        Object[] parm = {(pages-1)*counts,counts};
        String sql = "select * from product where pstatus=1 limit ?,?";
        try {
            List<ProductBean> allProducts = queryRunner.query(sql, new BeanListHandler<ProductBean>(ProductBean.class),parm);
            return allProducts;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public Long findCount() throws SQLException {
        DataSource ds = GetDataSourceUtil.getDataSource();
        QueryRunner queryRunner = new QueryRunner(ds);
        return queryRunner.query("select count(*) from product where pstatus=1", new ScalarHandler<Long>());
    }

}
